import express from 'express';
import compression from 'compression';
import webpack from 'webpack';
import webpackConfig from '../webpack.config';
import session from 'express-session';
import cookieParser from 'cookie-parser';
import render from './render';
import fs from 'fs';
import md5 from 'md5';
import proxy from 'http-proxy-middleware';
import './DateFormat';

const app = express();
const isDev = process.env.NODE_ENV === 'develpoment';
const secure = md5('PL-MOBILE-HOME');
let chunks = [];
const options = {
  target: 'http://api.houym.com',
  changeOrigin: true,
  ws: true,
  pathRewrite: {
    '^/api/old-path': '/api/new-path',
    '^/api/remove/path': '/path'
  }
};
if (isDev) {
  options.target = 'http://localhost:8080';
}
app.use(compression());
app.use('/api', proxy(options));

app.use(cookieParser(secure, {
  httpOnly: true,
  secure: false,
  maxAge: 60 * 60,
}));
app.use(session({
  name: secure,
  secret: secure,
  cookie: {maxAge: 60 * 60}
}));
if (isDev) {
  const webpackDevMiddleWare = require('webpack-dev-middleware');
  const webpackHotMiddleWare = require('webpack-hot-middleware');
  const compiler = webpack(webpackConfig);
  app.use(webpackDevMiddleWare(compiler, {
    noInfo: true,
    publicPath: webpackConfig.output.publicPath,
    serverSideRender: true,
    aggregateTimeout: 300,
    poll: true,
    stats: {
      chunks: false
    }
  }));
  app.use(webpackHotMiddleWare(compiler));
} else {
  chunks = JSON.parse(fs.readFileSync(webpackConfig.output.path + '/chunkNames.json'));
}
app.use(express.static(webpackConfig.output.path));
app.get('/**', async (req, res, next) => {
  const url = req.originalUrl;
  const token = req.cookies.token;
  if (!token && !url.startsWith('/login')) {
    return res.redirect('/login');
  }
  if (token && url !== '/') {
    return res.redirect('/');
  }
  isDev && (chunks = res.locals.webpackStats.toJson().assetsByChunkName || {});
  res.send(render(req, chunks));
});

const server = app.listen(5001, function () {
  const port = server.address().port;
  console.log("应用实例，访问地址为 http://localhost:%s", port)
});
